package client;

import client_commands.Command;
import client_commands.CommandExecutor;
import client_commands.CommandFactory;

/**
 * Thread zaduzen za citanje poruke iz stream-a i njihovo upisivanje u odgovarajuci buffer.
 * Poruka se upisuje u onaj buffer ciji se index dobija pozivom getBufferIndex() za objekat
 * connection. Ovaj index je setovan pozivanjem setMessage() metode, ciji je jedan od
 * argumenata index buffer-a koji koristi komanda koja je pozvala setMessage().
 * Thread je blokiran u readData() metodi, dok iz stream-a ne stigne neki podatak.
 * 
 * @author UrosKrkic & Radivoje Popovic
 */
public class ClientThreadReader extends Thread {
	
	
	/**
	 * Referenca na socket konekciju.
	 */
	private ClientSocketConnection connection;
	
	private ClientApplication theApp;
	
	
	/**
	 * Konstruktor.
	 * @param connection - referenca na socket konekiciju
	 * @author UrosKrkic & Radivoje Popovic
	 */
	public ClientThreadReader(ClientApplication theApp, ClientSocketConnection connection) {
		this.theApp = theApp;
		this.connection = connection;
		this.start();
	}
	
	
	@Override
	public void run() {
		
		String response;
		
		Command command;
		
		while ( (response = connection.readData()) != null ) {
			// TODO obrisati
//			System.out.println("CLIENT RECEIVED = " + response);
			
			// sada ne mora - reseno je u quitConnection() sa shutdownInput(), shutdownOutput()
//			if ( response.contains(Long.toString(this.connection.getConnectionID())) ) {
//				break;
//			}
		
			command = CommandFactory.createCommand(response);
			
			if (command == null) {
				connection.buffers[connection.getBufferIndex()].write(response);
			}
			else {
				new CommandExecutor(theApp, command);
			}
		}
	}
	
}
